package com.monlyu.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.math.RandomUtils;

import com.monlyu.bean.AuthCodeBean;
import com.monlyu.util.WebOptUtil;

public class AuthCodeServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		service(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	// 验证码图片的宽度。
	private int width;
	// 验证码图片的高度。
	private int height;
	private int x = 0;
	// 字体高度
	private int fontHeight;
	private int codeY;
	private final static char[] BIG_LETTERS = { 'A', 'B', 'C', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
			'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
	private final static char[] SMALL_LETTER = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
	private final static char[] NUMBERS = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };

	protected void service(HttpServletRequest request, HttpServletResponse response) {
		final AuthCodeBean bean = WebOptUtil.APP_ARGS.getAuthCode();
		this.width = NumberUtils.toInt(request.getParameter("width"), 93);
		this.height = NumberUtils.toInt(request.getParameter("height"), 23);
		x = width / (bean.getLength() + 1);
		codeY = height - 2;
		fontHeight = height - 2;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics2D graphics = image.createGraphics();
		graphics.setBackground(Color.WHITE);
		graphics.fillRect(0, 0, width, height);
		graphics.setFont(new Font("Fixedsys", Font.PLAIN, fontHeight));
		graphics.setColor(Color.DARK_GRAY); // 话边框
		graphics.drawRect(0, 0, width - 1, height - 1);
		// 产生干扰线
		if (bean.isNeedLines()) {
			for (int i = 0; i < 15; i++) {
				int x = RandomUtils.nextInt(width);
				int y = RandomUtils.nextInt(height);
				int xl = RandomUtils.nextInt(12);
				int yl = RandomUtils.nextInt(12);
				graphics.drawLine(x, y, x + xl, y + yl);
			}
		}
		char[] CHARSET_AREA = null;
		if (bean.getType().charAt(0) == '1') {
			CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, BIG_LETTERS);
		}
		if (bean.getType().charAt(1) == '1') {
			CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, SMALL_LETTER);
		}
		if (bean.getType().charAt(2) == '1') {
			CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, NUMBERS);
		}
		StringBuilder randomCode = new StringBuilder();
		int red = 0, green = 0, blue = 0;
		for (int i = 0; i < bean.getLength(); i++) {
			String rand = "" + CHARSET_AREA[RandomUtils.nextInt(CHARSET_AREA.length)];
			red = RandomUtils.nextInt(255);
			green = RandomUtils.nextInt(255);
			blue = RandomUtils.nextInt(255);
			graphics.setColor(new Color(red, green, blue));
			graphics.drawString(rand, (i + 1) * x, codeY);
			randomCode.append(rand);
		}
		HttpSession session = request.getSession();
		session.setAttribute("AuthCode", randomCode.toString());
		// 禁止图形缓存
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		try {
			// 将图形输出到Servlet流中
			ServletOutputStream sos = response.getOutputStream();
			ImageIO.write(image, "jpeg", sos);
			sos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
